<template>

</template>

<script>
	var _this = null;
	const api = require('api.js');
	export default {
		data() {
			return {
				code: null,
				isSuccess: false,
				uploading: false,
				faceTimer: null,
				timer: null,
				failTimes: 0
			}
		},
		methods: {
			uploadFace(e) {
				api.uploadFile('/api/user/face/loginByFace/' + _this.code, e, (res) => {
					var response = JSON.parse(res.data);
					if (response.code == 200 && (response.data != undefined || response.data != null)) {
						_this.isSuccess = true;
						api.updateToken(response.data.token);
						uni.redirectTo({
							url: '../index/index'
						})
						uni.showToast({
							icon: 'success',
							title: "登录成功",
							duration: 2000
						});
					} else {
						_this.failTimes += 1;
						if (_this.failTimes >= 10) {
							uni.redirectTo({
								url: '../index/index'
							});
							uni.showToast({
								icon: 'error',
								title: "请重新识别",
								duration: 2000
							});
						}
					}
					_this.uploading = false;
				}, (error) => {
					_this.uploading = false;
					_this.failTimes += 1;
					if (_this.failTimes >= 10) {
						uni.redirectTo({
							url: '../index/index'
						});
						uni.showToast({
							icon: 'error',
							title: "请重新识别",
							duration: 2000
						});
					}
				});
			},
			snapshotFace() {
				if (_this.isSuccess || _this.uploading) {
					return;
				}
				_this.uploading = true;
				_this.pusher.preview();
				_this.pusher.snapshot(function(e) {
					_this.uploadFace(e.tempImagePath);
				}, function(e) {
					
				})
			},
			initPusher() {
				const currentWebview = this.$mp.page.$getAppWebview();
				_this.pusher = plus.video.createLivePusher('pusher', {
					url: '',
					mode: 'FHD',
					muted: 'true',
					top: '0px',
					left: '0px',
					aspect: '9:16'
				});
				currentWebview.append(_this.pusher);
				_this.pusher.start();
				_this.pusher.switchCamera();
				var wv = plus.webview.create("", "custom-webview", {
					plusrequire: 'none',
					background: 'transparent',
					'uni-app': 'none',
				});
				wv.loadURL('/static/face/face.html');
				currentWebview.append(wv);
				_this.pusher.preview();
				_this.timer = setInterval(function() {
					return _this.snapshotFace();
				}, 1500);
			},
			initFace() {
				uni.showLoading({
					title: '正在打开摄像头'
				});
				api.getSync('/api/user/face/create?type=face_scanner', {},
					res => {
						_this.code = res.data.code;
					},
					error => {
						uni.showToast({
							icon: 'error',
							title: "网络异常",
							duration: 2000
						})
					});
				_this.faceTimer =
					setTimeout(() => {
						_this.initPusher();
						uni.hideLoading();
					}, 1000);
			}
		},
		onLoad() {
			_this = this;
		},
		onReady() {
			_this.initFace();
		},
		onUnload() {
			_this.pusher.stop();
			if (_this.timer != null) {
				clearInterval(_this.timer);
			}
			if (_this.faceTimer != null) {
				clearTimeout(_this.faceTimer);
			}
		}
	}
</script>

<style>

</style>
